<template>
  <div class="container">
    <topTitle
      :titleText="titleText"
      :back="back"
      @gobackTriser="goBack"
    ></topTitle>
    <div class="mainCon">
      <el-form
        :model="formData"
        :rules="formRules"
        ref="formData"
        label-width="174px"
        class="demo-formData"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item
              prop="projectName"
              label="项目名称："
              class="row-padding-bottom projectName"
            >
              <el-input
                v-model="formData.projectName"
                placeholder="请输入项目名称"
                clearable
                @input="changeProjectName"
                class="lWidth"
              ></el-input>
              <div v-if="projectNameFlag" class="commonStyle">
                <template v-for="(item, index) in likeProjects">
                  <p
                    :key="index"
                    @click="clickShowCompany(index)"
                    ref="projectName"
                  >
                    {{ item.projectName || '--' }}
                  </p>
                </template>
              </div>
              <div class="commonStyle" v-if="companyNameFlag">
                <el-radio-group
                  v-model="companyRadio"
                  @change="changeCompanyRadio"
                >
                  <template v-for="(item, index) in projectCompanys">
                    <el-radio
                      :key="index"
                      :label="index"
                      :style="{ display: 'block' }"
                      >{{ item.type }}：{{ item.companyName }}</el-radio
                    >
                  </template>
                </el-radio-group>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item
              prop="industryId"
              label="行业："
              class="row-padding-bottom"
            >
              <el-select
                v-model="formData.industryId"
                filterable
                placeholder="请选择"
                clearable
                class="lWidth"
              >
                <el-option
                  v-for="item in industryOptions"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item
              v-bind:prop="companyName"
              label="责任主体企业名称："
              class="row-padding-bottom"
            >
              <el-input
                type="text"
                v-model="formData.companyName"
                placeholder="请输入责任主体企业名称"
                class="lWidth"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item
              prop="uscc"
              label="责任主体社会信用代码："
              class="row-padding-bottom"
            >
              <el-input
                type="text"
                v-model="formData.uscc"
                placeholder="请输入责任主体社会信用代码"
                @change="checkSetCompnyName"
                clearable
                class="lWidth"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item
              prop="transactor"
              label="企业负责人姓名："
              class="row-padding-bottom"
            >
              <el-input
                v-model="formData.transactor"
                clearable
                placeholder="请输入企业负责人姓名"
                class="sWidth"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item
              prop="transactorTel"
              label="企业负责人联系方式："
              class="row-padding-bottom"
            >
              <el-input
                v-model="formData.transactorTel"
                clearable
                placeholder="请输入企业负责人联系方式"
                class="sWidth"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item
              prop="status"
              label="奖惩情况："
              class="row-padding-bottom"
            >
              <el-select
                v-model="formData.status"
                filterable
                placeholder="请选择"
                clearable
                class="sWidth"
              >
                <el-option
                  v-for="item in rewardList"
                  :key="item.id"
                  :label="item.text"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item
              prop="areaId"
              label="监管区域："
              class="row-padding-bottom"
            >
              <el-cascader
                ref="manageArea"
                :show-all-levels="false"
                class="lWidth"
                v-model="areaId"
                :options="areasOptions"
                @change="getAreaId"
                clearable
                filterable
              ></el-cascader>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item
              :prop="isCzUser() ? '' : 'startDate'"
              label="奖惩时间："
              class="row-padding-bottom"
            >
              <el-date-picker
                v-model="formData.startDate"
                type="date"
                placeholder="选择日期"
                clearable
                value-format="yyyy-MM-dd"
                class="sWidth"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item
              :prop="isCzUser() ? '' : 'endDate'"
              label="奖惩时间截止至："
              class="row-padding-bottom"
            >
              <el-date-picker
                v-model="formData.endDate"
                type="date"
                placeholder="选择日期"
                clearable
                value-format="yyyy-MM-dd"
                class="sWidth"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="isCzUser()">
          <el-col>
            <el-form-item label="清退出滁州市场：">
              <el-radio-group v-model="formData.isClear">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
              <span style="color: #409eff; padding-left: 12px"
                >说明：单选框选择是，该企业不允许再参与滁州市工程建设领域项目建设，目前已参建的项目不做变动</span
              >
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item
                label="奖惩原因："
                prop="reason"
                class="row-padding-bottom"
              >
                <el-input
                  type="textarea"
                  :rows="5"
                  v-model="formData.reason"
                  id="homeAddress"
                  placeholder="请输入奖惩原因，200字符以内"
                  clearable
                  :style="{ width: '88%' }"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row class="row-padding-bottom">
            <el-col :span="24" class="col-position">
              <el-form-item
                label="上传奖惩资料："
                prop="content"
                class="content"
                label-width="174px"
              >
                <uploadAnnex
                  @getFileList="getFileList"
                  :limitationFactor="limitationFactor"
                  @getFile="getFile"
                  :upLoadFile="upLoadFile"
                />
                <!-- <ul class="upLoadFile">
                  <li v-for="(item,index) of upLoadFile" :key="index">
                    <i class="icon iconfont iconfujian"></i>
                    {{item.name}}
                    <span class="del" @click="delFile(index)">删除</span>
                  </li>
                </ul> -->
              </el-form-item>
              <el-row v-model="formData.senderFileJson">
                <uploadResult
                  style="margin-left: 174px !important"
                  :resultList="upLoadFile"
                  @callBackResult="getFile"
                />
              </el-row>
            </el-col>
          </el-row>
        </el-row>
        <div class="submitBox">
          <el-button
            type="primary"
            class="commonBut saveBtn"
            @click.native="saveForm"
            v-show="isShowSave"
            :loading="isSaveLoading"
            >保存</el-button
          >
          <el-button class="commonBut" @click="goBack">取消</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>
<script>
import { mapActions, mapState } from 'vuex'
export default {
  name: 'addReward',
  data() {
    var checkArea = (rule, value, callback) => {
      var that = this
      if (!that.formData.areaId) {
        return callback(new Error('发生地区不能为空'))
      } else {
        callback()
      }
    }
    //验证uscc
    var validateUscc = (rule, value, callback) => {
      if (value == '' || value == null) {
        callback()
      } else {
        var regUscc = /^[0-9A-Z]{2}[0-9]{6}[0-9A-Z]{10}$/
        if (!regUscc.test(value)) {
          callback(new Error('统一社会信用代码格式不正确'))
        } else {
          callback()
        }
      }
    }
    //验证项目名称
    var validateProjectName = (rule, value, callback) => {
      value = value.replace(/\s+/g, '')
      if (value === '') {
        callback(new Error('项目名称不能为空'))
      } else if (!this.formData.projectName) {
        callback(new Error('请选择展示的项目名称'))
      } else {
        callback()
      }
    }
    //
    var checkStartDate = (rule, value, callback) => {
      if (value == '') {
        return callback(new Error('请选择奖惩开始时间'))
      } else {
        if (
          this.formData.endDate &&
          this.compareDate(value, this.formData.endDate)
        ) {
          return callback(new Error('奖惩开始时间不能大于结束时间'))
        }
        this.$refs.formData.clearValidate('endDate')
        callback()
      }
    }
    var checkEndDate = (rule, value, callback) => {
      if (value == '') {
        return callback(new Error('请选择奖惩结束时间'))
      } else {
        if (
          this.formData.startDate &&
          this.compareDate(this.formData.startDate, value)
        ) {
          return callback(new Error('奖惩结束时间不能小于开始时间'))
        }
        this.$refs.formData.clearValidate('startDate')
        callback()
      }
    }
    return {
      limitationFactor: {
        uploadAnnexUrl: 'api-f/files/upload', //自定义上传文件接口地址
        upLoadFileLength: 10, //自定义上传文件最大数量设置
        fileSize: 10, //自定义上传文件最大设置
        messageFileSizetip: '最多能上传10M以内的附件', //自定义id解决一个页面包含多个上传附件
        messagetip: '附件为文档或pdf文件，大小不超过10M', //自定义报错提示语
        formatType: 'typeTwo', //自定义上传格式校验类型
        fileId: 'uploadFileInput', //自定义id解决一个页面包含多个上传附件
        uploadFormId: 'uploadFileForm', //自定义id解决一个页面包含多个上传附件
        methodTip: '附件为文档或pdf文件', //自定义上传文件提示
        uploadBtnType: 'typeOne', //自定义上传按钮类型
      },
      titleText: '新增企业奖惩',
      back: true,
      likeProjects: [],
      selectProject: [],
      projectCompanys: [],
      projectNameFlag: false,
      companyNameFlag: false,
      companyRadio: '',
      upLoadFile: [],
      uploadUrl: 'api-f/files/upload',
      oldSrcList: [],
      dialogImageUrl: '',
      srcList: [],
      areaId: '',
      isSaveLoading: false, // 保存loading
      formData: {
        id: '',
        projectName: '', //--项目名称
        projectId: '', //--项目Id
        industryId: '', //--行业ID
        companyName: '', //--责任主体企业名称
        uscc: '', //--责任主体企业USCC
        transactor: '',
        transactorTel: '',
        startDate: '', //2019/11/19--事件发生日期
        endDate: '',
        status: '', //奖惩情况
        reason: '', //--奖惩原因
        areaId: '', //--1502区域Id
        areaName: '',
        fileJson: [],
        isClear: 0, //是否清退
      },
      rewardList: [], //奖惩情况列表（枚举）
      formRules: {
        uscc: [{ validator: validateUscc, trigger: 'blur' }],
        areaId: [{ required: true, validator: checkArea, trigger: 'change' }],
        startDate: [
          { required: true, validator: checkStartDate, trigger: 'change' },
        ],
        endDate: [
          { required: true, validator: checkEndDate, trigger: 'change' },
        ],
        industryId: [
          { required: true, message: '行业不能为空', trigger: 'change' },
        ],
        status: [
          { required: true, message: '奖惩情况不能为空', trigger: 'change' },
        ],
        projectName: [
          { required: true, validator: validateProjectName, trigger: 'blur' },
        ],
        reason: [
          { required: true, message: '奖惩原因不能为空', trigger: 'change' },
          { min: 1, max: 200, message: '奖惩原因不超过200字', trigger: 'blur' },
        ],
        transactor: [
          {
            min: 2,
            max: 20,
            message: '最少输入2个汉字，最多输入20个汉字',
            trigger: 'blur',
          },
        ],
        transactorTel: [
          {
            pattern: /^1[3456789]\d{9}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur',
          },
        ],
      },
      isShowSave: '',
      projectCompany: '', //当前选中
    }
  },
  computed: { ...mapState(['areasOptions', 'industryOptions']) },
  watch: {
    'formData.projectName': {
      handler(newVal, oldVal) {
        if (newVal) {
          this.$refs.formData.clearValidate('projectName')
          this.$refs.formData.clearValidate('uscc')
        }
        if (!newVal) {
          this.likeProjects = []
          this.projectNameFlag = false
          this.companyNameFlag = false
        }
      },
    },
  },
  created: function () {
    //字典表下拉框
    this.getAreas({ areaId: this.$store.state.areaInfoArr.areaId })
    this.companyNameFlag = false
    this.projectNameFlag = false
    this.companyRadio = ''
    this.getIndustry({})
    this.getReawardList()
    this.isShowSave =
      this.$store.state.buttonLimitsArr.indexOf('importEvent:add') > -1
  },
  mounted() {
    if (this.$route.query.id) {
      this.titleText = '修改企业奖惩'
      this.formData.id = this.$route.query.id
      this.getRewardDetail()
    } else {
      this.titleText = '新增企业奖惩'
    }
  },
  methods: {
    ...mapActions(['getAreas', 'getIndustry']),
    /**
     * @description: 奖惩情况列表
     */
    getReawardList() {
      this.axios.post('api-r/reward/expand/findstatusenum').then((res) => {
        if (!res.data.hasError) {
          this.rewardList = res.data.result
        }
      })
    },
    /**
     * @description: 比较2个日期大小
     */
    compareDate(startDate, endDate) {
      let oDate1 = new Date(startDate)
      let oDate2 = new Date(endDate)
      if (oDate1.getTime() > oDate2.getTime()) {
        return true
      }
      return false
    },
    /**
     * @description: 获取上传的附件
     */
    getFileList(val) {
      this.oldSrcList.push(val)
      this.srcList.push(val)
    },
    /**
     * @description: 获取上传的附件
     */
    getFile(val) {
      this.upLoadFile = val
    },
    delFile(index) {
      this.upLoadFile.splice(index, 1)
    },
    /**
     * @description: 根据id查询奖惩明细
     */
    getRewardDetail() {
      this.axios
        .get('api-r/reward/expand/detail', { params: { id: this.formData.id } })
        .then((res) => {
          if (!res.data.hasError) {
            let obj = res.data.result
            const {
              id,
              projectName,
              projectId,
              industryId,
              companyName,
              uscc,
              transactor,
              transactorTel,
              startDate,
              endDate,
              status,
              reason,
              areaId,
              areaName,
              fileList,
              isClear = 0,
            } = obj
            this.areaId = areaId
            this.upLoadFile = fileList
            this.formData = {
              id,
              projectName, //--项目名称
              projectId, //--项目Id
              industryId, //--行业ID
              companyName, //--责任主体企业名称
              uscc, //--责任主体企业USCC
              transactor,
              transactorTel,
              startDate, //2019/11/19--事件发生日期
              endDate,
              status, //奖惩情况
              reason, //--奖惩原因
              areaId, //--1502区域Id
              areaName,
              fileJson: fileList,
              isClear,
            }
          }
        })
    },
    saveForm() {
      var files = []
      this.upLoadFile.forEach((item) => {
        let pathStr = item.path
        let newName = pathStr.substr(
          pathStr.lastIndexOf('/') + 1,
          pathStr.length - 1
        )
        let fileType = pathStr.substr(
          pathStr.lastIndexOf('.') + 1,
          pathStr.length - 1
        )
        files.push({
          id: item.id,
          originalName: item.name,
          size: item.size,
          newName: newName,
          relativePath: item.path,
          name: item.name,
          url: item.path,
          assicuateName: 'T_CS_RIGHTSACCIDENT',
          assicuateId: '-1',
          fileType: fileType,
          isImg: item.isImg,
          contentType: item.contentType,
          path: item.path,
          source: item.source,
          createTime: item.createTime,
        })
      })
      this.formData.fileJson = JSON.stringify(files)
      this.$refs.formData.validate((valid) => {
        if (valid) {
          this.saveFormInfo()
        } else {
          return false
        }
      })
    },
    saveFormInfo() {
      this.isSaveLoading = true
      this.axios({
        method: 'post',
        url: 'api-r/reward/expand/saveoreditcom',
        data: this.formData,
      })
        .then((response) => {
          this.isSaveLoading = false
          if (!response.data.hasError) {
            this.$message({
              type: 'success',
              message: '保存成功',
            })
            this.formVisible = false
            this.$router.push({
              path: '/home/events/rewardAndPunish',
              query: { activeName: 1 },
            })
            this.$store.commit('GOBACK_NAME', {
              oldUrl: '/home/events/rewardAndPunish',
              newUrl: this.$router.currentRoute.fullPath,
            })
          } else {
            this.$message({
              type: 'error',
              message: response.data.errorMsg,
            })
            this.isSaveLoading = false
          }
        })
        .catch((error) => {
          this.$message.error('保存失败')
          this.isSaveLoading = false
        })
    },
    goBack() {
      this.$refs['formData'].resetFields()
      this.$router.push({
        path: '/home/events/rewardAndPunish',
        query: { activeName: 1 },
      })
      // this.$store.commit("CHANGE_SLIDER_NAME", {
      //     oldUrl: "/home/events/rewardAndPunish",
      //     newUrl: this.$router.currentRoute.fullPath
      // });
      this.$store.commit('GOBACK_NAME', {
        oldUrl: '/home/events/rewardAndPunish',
        newUrl: this.$router.currentRoute.fullPath,
      })
    },

    getSelecData(type) {
      var url = 'api-bs/base/dicitem/findbytype'
      this.axios({
        method: 'post',
        url: url,
        data: { type },
      })
        .then((res) => {
          if (type == 'RIGHTS_TYPE') {
            this.type = res.data.result
          }
        })
        .catch((error) => {
          this.$message({
            showClose: true,
            duration: 3000,
            message: '获取数据失败',
            type: 'error',
          })
        })
    },
    //行业
    getIndustryId() {
      this.formData.industryId =
        this.formData.industryId[this.formData.industryId.length - 1]
    },

    //获取选中的区域最后一级id
    getAreaId(val) {
      var areaId = this.areaId[this.areaId.length - 1]
      this.formData.areaId = areaId
      this.formData.areaName = this.$refs.manageArea.getCheckedNodes()[0].label
    },

    changeProjectName() {
      this.likeProjects = []
      this.formData.uscc = ''
      this.formData.companyName = ''
      this.formData.projectId = ''
      //没有输入的时候不请求
      if (!this.formData.projectName) {
        this.projectNameFlag = false
        this.companyNameFlag = false
        return false
      }
      this.axios({
        method: 'post',
        url: 'api-p/project/expand/likeproject',
        data: { projectName: this.formData.projectName },
      })
        .then((resp) => {
          if (!resp.data.hasError) {
            var listTemps = resp.data.result.results
            if (listTemps.length > 5) {
              for (var i = 0; i < 5; i++) {
                this.likeProjects.push(listTemps[i])
              }
            } else {
              this.likeProjects = listTemps
            }
            if (this.likeProjects.length > 0) {
              this.projectNameFlag = true
              this.companyNameFlag = false
              this.companyRadio = ''
            }
          }
        })
        .catch((resp) => {
          this.$message.error('数据获取失败')
        })
    },
    checkSetCompnyName() {
      //手动去修改已经自动导入的USCC的话，清空主键id
      if (
        this.projectCompany.uscc !== this.formData.uscc &&
        this.formData.uscc !== ''
      ) {
        this.formData.projectCompanyId = ''
      }
      this.axios({
        method: 'post',
        url: 'api-p/projectcompany/expand/findcompanyname',
        data: { uscc: this.formData.uscc },
      })
        .then((resp) => {
          if (!resp.data.hasError) {
            this.formData.companyName = resp.data.result
          }
        })
        .catch((resp) => {
          this.$message.error('数据获取失败')
        })
    },

    clickProjectName() {
      this.projectNameFlag = true
      this.companyNameFlag = false
      this.companyRadio = ''
    },
    clickShowCompany(index) {
      this.selectProject = this.likeProjects[index]
      this.formData.projectId = this.selectProject.id
      this.axios({
        method: 'post',
        url: 'api-p/projectcompany/expand/findtypebyprojectid',
        data: { projectId: this.selectProject.id },
      })
        .then((resp) => {
          if (!resp.data.hasError) {
            this.projectCompanys = resp.data.result
          }
        })
        .catch((resp) => {})

      this.formData.projectName = this.selectProject.projectName
      this.companyNameFlag = true
      this.projectNameFlag = false
      this.companyRadio = ''
    },
    changeCompanyRadio(label) {
      this.projectCompany = this.projectCompanys[label]
      const { id, uscc, companyName, manager, managerTel } = this.projectCompany
      this.formData.projectCompanyId = id
      this.formData.uscc = uscc //--责任主体社会信用代码
      this.formData.companyName = companyName //--责任主体企业名称
      this.formData.transactor = manager //--企业负责人姓名
      this.formData.transactorTel = managerTel //--企业负责人联系方式
    },
  },
}
</script>
<style scoped lang="less">
// 上传文件
.upLoadFile {
  color: #333;
  line-height: 21px;
  li {
    margin-bottom: 10px;
    i {
      color: #999;
      margin: 0 5px 0 15px;
    }
    .del {
      font-size: 14px;
      color: #db0202;
      margin-left: 20px;
      cursor: pointer;
    }
  }
}

.container {
  .mainCon {
    padding: 40px 80px 40px 20px;
    .submitBox {
      margin-left: 174px;
      margin-top: 18px;
    }
    .projectName {
      .commonStyle {
        z-index: 999;
      }
      ul {
        position: relative;
        background: #fff;
        width: 320px;
        min-height: 80px;
        top: 5px;
        left: 0;
        margin-bottom: 12px;
        padding: 12px;
        z-index: 2000;
        color: #606266;
        line-height: 1.4;
        font-size: 14px;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        word-break: break-all;
        transform-origin: center top;
        border-radius: 4px;
        border: 1px solid #ebeef5;
        li {
          padding: 12px 0;
          &:hover {
            background: #f8f8f8;
            cursor: pointer;
          }
        }
      }
      .el-radio {
        padding: 8px 0;
      }
    }
  }
}
form.el-form.demo-formData {
  width: 100%;
  display: inline-block;
  text-align: left;
  .infoTitle {
    font-size: 16px;
    padding: 16px 24px;
    background: #f5f7fb;
    margin-bottom: 24px;
    color: #333;
    font-weight: 700;
  }
  .proInputWidth {
    width: 70%;
  }
}
.saveBtn {
  background-color: #009588;
  border-color: #009588;
  color: #fff;
}
</style>
